package zestaw1.zmienna_ilosc_parametrow_v2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Author: Daniel Michalski
 * Date: 13.07.13
 */

public class ReflectionTest extends JFrame implements ActionListener {
    Method currAction = null;   // biezaca metoda obslugi
    Class actionClass = null;   // klasa obslugi
    Object actionObject = null; // obiekt obslugi
    JPopupMenu popUp = null;    // menu kontekstowe z wyborem obslugi
    JButton b;

    public ReflectionTest() {
        super("Test refleksji");
        try {
            actionClass = Class.forName("zestaw1.zmienna_ilosc_parametrow_v2.ActionSet");
            actionObject = actionClass.newInstance();
        } catch (Exception ex) {
            throw new RuntimeException("Wadliwa klasa obslugi");
        }

        popUp = new JPopupMenu();
        createMenuItems();

        b = new JButton("Użyj prawego przycisku myszy, by ustalic akcje.");
        b.setFont(new Font("Dialog", Font.BOLD, 24));
        b.addActionListener(this);
        b.setComponentPopupMenu(popUp);

        setLayout(new FlowLayout());
        add(b);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void createMenuItems() {
        Method[] mets = null;
        try {
            mets = actionClass.getMethods();
        } catch (Exception ex) {
            throw new RuntimeException("Niedostepna info o metoda klasy obslugi");
        }

        for (Method m : mets) {
            if (m.getDeclaringClass() == actionClass) {
                String name = m.getName();
                JMenuItem mi = new JMenuItem(name);
                mi.addActionListener(this);
                popUp.add(mi);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object src = e.getSource();
        if (src instanceof JMenuItem)
            setCurrentAction(((JMenuItem)src).getText());
        else {
            try {
                currAction.invoke(actionObject);
            } catch (Exception e1) {
                JOptionPane.showMessageDialog(null, "Akcja na przycisku nie ustalona");
            }
        }
    }

    private void setCurrentAction(String action) {
        try {
            currAction = actionClass.getMethod(action);
            b.setText("Teraz akcją jest: " + currAction.getName() + " - kliknij");
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Nieznana metoda obslugi");
        }
    }

    public static void main(String[] args) {
        new ReflectionTest();
    }
}
